var grid;
Ext.onReady(function() {

    Ext.SSL_SECURE_URL = "../../ext-3.2.1/resources/images/default/s.gif";
    Ext.BLANK_IMAGE_URL = "../../ext-3.2.1/resources/images/default/s.gif";
    //    Ext.state.Manager.setProvider(new Ext.state.CookieProvider());
    document.all('currentTheme').value = currentTheme;
    Ext.util.CSS.swapStyleSheet('theme', currentTheme);
    Ext.QuickTips.init();
    Ext.form.Field.prototype.msgTarget = 'side';
    var pageSize = 20;
    var centerTabPanel = new Ext.TabPanel({
        region:'center',
        deferredRender:false,
        activeTab:1,
        margins:'0 5 0 0',
        //plugins: new Ext.ux.TabCloseMenu(),
        resizeTabs:false,
        minTabWidth: 50,
        //tabWidth:150,
        enableTabScroll:true,
        autoScroll:true,
        items:[{
            title: '下级标签：',
           // tabWidth:120,
           iconCls: 'tabsDown',
          //contentEl:'grid-div',
            disabled:true
           // autoScroll:true
        },
          {
            title: '码表名称列表维护',
            iconCls: 'tabs',
             //tabWidth:150,
            contentEl:'grid-div',
            autoScroll:true
        }
        ],
        loadPage: function(href, cls, title) {
            var tabId = 'workPanel' + cls;
            var tab = this.getComponent(tabId);
            if (tab) {
                this.setActiveTab(tab);
            } else {
                var autoLoad = {url: href,scripts: true};
                var p = this.add(new DocPanel({
                    id: tabId,
                    cclass : cls,
                    layout:'fit',
                    items: [ new IFrameComponent({ id: tabId, url: href }) ],
                    title: title,
                    iconCls: 'tabs'
                }));
                this.setActiveTab(p);
            }
        }
    });
    IFrameComponent = Ext.extend(Ext.BoxComponent, {
        onRender : function(ct, position) {
            this.el = ct.createChild({tag: 'iframe', id: 'iframe-' + this.id, frameBorder: 0, src: this.url});
        }
    });

    DocPanel = Ext.extend(Ext.Panel, {
        closable: true,
        autoScroll:true,
        initComponent : function() {
            DocPanel.superclass.initComponent.call(this);
        },
        scrollToMember : function(member) {
            var el = Ext.fly(this.cclass + '-' + member);
            if (el) {
                var top = (el.getOffsetsTo(this.body)[1]) + this.body.dom.scrollTop;
                this.body.scrollTo('top', top - 25, {duration:.75, callback: this.hlMember.createDelegate(this, [member])});
            }
        },
        scrollToSection : function(id) {
            var el = Ext.getDom(id);
            if (el) {
                var top = (Ext.fly(el).getOffsetsTo(this.body)[1]) + this.body.dom.scrollTop;
                this.body.scrollTo('top', top - 25, {duration:.5, callback: function() {
                    Ext.fly(el).next('h2').pause(.2).highlight('#8DB2E3', {attr:'color'});
                }});
            }
        },
        hlMember : function(member) {
            var el = Ext.fly(this.cclass + '-' + member);
            if (el) {
                el.up('tr').highlight('#cadaf9');
            }
        }
    });
    new Ext.Viewport(
    {
        region:'center',
        layout:'fit',
        items:centerTabPanel
    });
    // 性别
    var typeStore = new Ext.data.SimpleStore({
        fields : ['value', 'label'],
        data : [['1', '简单码表'], ['2', '树形码表']]
    });
   function renderBtn(val, p, record) {
		var contentId = Ext.id();
		createGridButton.defer(2, this, [2, "维护数据", contentId, record]);
		return ('<div id="' + contentId + '"></div>');
	}

    function createGridButton(index, value, contentid, record) {

			new Ext.Button({
				renderTo : contentid,
				text : value,
				handler : function(btn, e) {
					onManagerClick2( record.id);
				}, // 进入筛查
				cls : 'x-btn-text',
				scope : this
			});

	}

   function getRadios(store){
    var map=[]
        for (var i = 0; i < store.getCount(); i++) {
        map.push({boxLabel:store.getAt(i).data['label'],value:store.getAt(i).data['value']})
    }
    return map;
}

    function onManagerClick2(id) {

            //var record = item;
          //  var id = record.id;
          //  var record = sm.getSelected();
            centerTabPanel.loadPage('../dataDictionary/tddDataList' + gridStore.getById(id).data['ddType'] + '.jsp?ddId=' + id+'&ddtype='+gridStore.getById(id).data['ddtype'],
                   // gridStore.getById(id).data['code'], gridStore.getById(id).data['name']);
         gridStore.getById(id).data['code'], '选中码表进行维护');
        //}
    }
    function onManagerClick(item) {
        var selectedCount = sm.getCount();
        if (selectedCount == 0) {
            Ext.Msg.alert('维护数据', '未选中任何一条记录，请选择要维护的码表！');
            return;
        } else if (selectedCount > 1) {
            Ext.Msg.alert('维护数据', '只能选择一个码表，不能同时选择多条码表！');
            return;
        } else {
            var record = sm.getSelected();
            var id = record.id;
            var record = sm.getSelected();
            centerTabPanel.loadPage('../dataDictionary/tddDataList' + gridStore.getById(id).data['ddType'] + '.jsp?ddId=' + id,
                    gridStore.getById(id).data['code'], gridStore.getById(id).data['name']);
        }
    }

    var addButton = new Ext.Toolbar.Button({
        icon    : "../../ext-3.2.1/examples/shared/icons/fam/add.png",
        id      : 'addButton',
        cls: 'x-btn-text-icon',
        text    : '添加',
        tooltip : '添加一条新的记录',
        disabled: false,
        handler : onAddClick
    });
    var modButton = new Ext.Toolbar.Button({
        icon    : "../../ext-3.2.1/examples/shared/icons/fam/edit.png",
        id      : 'modButton',
        cls: 'x-btn-text-icon',
        text    : '修改',
        tooltip : '修改一条选中记录。',
        disabled: false,
        handler : onModClick
    });
    var delButton = new Ext.Toolbar.Button({
        icon    : "../../ext-3.2.1/examples/shared/icons/fam/del.png",
        id      : 'delButton',
        cls: 'x-btn-text-icon',
        text    : '删除',
        tooltip : '删除已选中的记录。',
        disabled: false,
        handler : onDelClick
    });
    var managerButon = new Ext.Toolbar.Button({
        icon    : "../../ext-3.2.1/examples/shared/icons/fam/manage.png",
        id      : 'managerButon',
        cls: 'x-btn-text-icon',
        text    : '维护代码表内容',
        tooltip : '维护选中码表内容。',
        disabled: false,
        handler : onManagerClick
    });
     var queryButton = new Ext.Toolbar.Button({
        icon    : "../../ext-3.2.1/examples/shared/icons/fam/query.png",
        id      : 'queryButton',
        cls: 'x-btn-text-icon',
        text    : '查询',
        disabled: false,
        tooltip : '查询记录',
        handler : onQueryClick
    });
   var nameQuery = new Ext.form.TextField({
            fieldLabel: '码表名称',
            id:'nameQuery',
           // name: 'name',
            width:160,
            maxLength:16,
            maxLengthText:"最大长度16",
            allowBlank:true
        });

   var  describeQuery = new Ext.form.TextField({
            fieldLabel: '码表说明',
            id:'describeQuery',
           // name: 'describe',
            width:200,
            maxLength:50,
            maxLengthText:"最大长度50"
        });

    var  idQuery = new Ext.form.TextField({
            fieldLabel: 'id',
            id:'idQuery',
           // name: 'describe',
            width:30,
            maxLength:15,
            maxLengthText:"最大长度15"
        });

    var formPanel ;
    var win;

    function onAddClick(item) {
        var name,code,dtype,describe,ordernum,remark;
        name = new Ext.form.TextField({
            fieldLabel: '码表名称',
            id:'name',
            name: 'name',
            width:200,
            maxLength:16,
            maxLengthText:"最大长度16",
            allowBlank:false
        });

       var  nbcode=new Ext.form.Hidden({
            fieldLabel: '编码',
            id:'nbcode',
            name: 'nbcode',
            width:100,
            maxLength:10,
            maxLengthText:"最大长度10",
            allowBlank:false
        });
        remark = new Ext.form.Hidden({
            fieldLabel: '开发公司',
            id:'remark',
            name: 'remark',
            width:200,
            maxLength:8,
            maxLengthText:"最大长度8",
            allowBlank:true
        });
        /*
        dtype = new Ext.form.Hidden({
            name:'ddType',
            value:'1'
        });
         */

        dtype = new Ext.ux.RadioGroup({
            fieldLabel : '类型',

			// xtype:'radiogroup',//表单文本框
			 horizontal:true,
			 maxLength : 200,
			 defaultValue:'1',
			 name :'ddType',
			 radios:getRadios(typeStore)
        });
        describe = new Ext.form.TextField({
            fieldLabel: '码表说明',
            id:'describe',
            name: 'describe',
            width:300,
            maxLength:50,
            maxLengthText:"最大长度50"
        });
        code =new Ext.form.TextField({
            fieldLabel: '编码',
            id:'code',
            name: 'code',
            width:200,
            maxLength:20,
            maxLengthText:"最大长度20"
        });
        ordernum = new Ext.form.Hidden({
            fieldLabel: '码表编号',
            id:'ordernum',
            name: 'ordernum',
            width:100,
            maxLength:4,
            maxLengthText:"最大长度4",
            allowBlank:false
        });
        if (formPanel != null) {
            formPanel.destroy(true);
            formPanel = null;
        }
        if (!formPanel) {
            formPanel = new Ext.FormPanel({
                labelWidth: 125,
                labelAlign:"right",
                url: '../../dataDictionary/createTddDefinition.action',
                frame:false,
                bodyStyle:'padding:60px 5px 0',
                items: [code ,nbcode,ordernum,name,dtype,describe,remark]
            });
        }
        if (win != null) {
            win.destroy(true);
            win = null;
        }
        if (!win) {
            win = new Ext.Window({
                id : 'formWin',
                title: '添加记录',
                width: 520,
                height:370,
                minWidth: 200,
                minHeight: 200,
                xtype:'window',
                maximizable : false,
                closeAction : 'hide',
                layout: 'fit',
                plain:false,
                closable:true,
                modal:false,
                border:false,
                bodyStyle:'padding:5px;',
                buttonAlign:'center',
                items: formPanel,
                buttons: [{
                    handler: function() {
                        if (formPanel.getForm().isValid()) {
                            formPanel.getForm().submit({
                                waitMsg: '正在处理，请稍等...',
                                reset: true,
                                failure: function(form, action) {
                                    Ext.MessageBox.hide();
                                    Ext.Msg.show({
                                        title: '错误',
                                        msg: '<span style="text-align:center;width:250px;margin:5 0 5 0;">' + action.result.msg + '</span>',
                                        buttons: Ext.MessageBox.OK,
                                        icon: Ext.MessageBox.WARNING
                                    });
                                },
                                success: function(form, action) {
                                    Ext.MessageBox.hide();
                                    Ext.Msg.show({
                                        title: '成功',
                                        msg: '<span style="text-align:center;width:250px;margin:5 0 5 0;">' + action.result.msg + '</span>',
                                        buttons: Ext.MessageBox.OK,
                                        icon: Ext.MessageBox.INFO
                                    });
                                    win.hide();
                                    gridStore.reload();
                                },
                                method:'POST'
                            });
                        }
                    },
                    text: '保存'
                },{
                    handler: function() {
                        win.hide();
                    },
                    text: '取消'
                }]
            });
        }
        win.show();
    }

    var modformPanel ;
    var modwin;

    function onModClick(item) {
        var selectedCount = sm.getCount();
        if (selectedCount == 0) {
            Ext.Msg.alert('修改记录', '未选中任何一条记录，请选择要修改的记录！');
            return;
        } else if (selectedCount > 1) {
            Ext.Msg.alert('修改记录', '只能选择一条记录，不能同时选择多条记录！');
            return;
        } else {
            var record = sm.getSelected();
            var id = record.id;
            var name,code,dtype,describe,ordernum,ddId;
            name = new Ext.form.TextField({
                fieldLabel: '码表名称',
                id:'modname',
                name: 'name',
                width:200,
                maxLength:16,
                maxLengthText:"最大长度16",
                allowBlank:false,
                value:gridStore.getById(id).data['name']
            });

             var  nbcode=new Ext.form.Hidden({
            fieldLabel: '编码',
            id:'modnbcode',
            name: 'nbcode',
            width:100,
            maxLength:10,
             value:gridStore.getById(id).data['nbcode'] ,
            maxLengthText:"最大长度10",
            allowBlank:false
        });
            var remark = new Ext.form.Hidden({
                fieldLabel: '开发公司',
                id:'modremark',
                name: 'remark',
                width:200,
                maxLength:8,
                //qtip:'码表关键字段，必须唯一，不能重复！',
                maxLengthText:"最大长度8",
               // allowBlank:false,
                value:gridStore.getById(id).data['remark']
            });
            describe = new Ext.form.TextField({
                fieldLabel: '码表说明',
                id:'moddescribe',
                name: 'describe',
                width:300,
                maxLength:50,
                maxLengthText:"最大长度50",
                value:gridStore.getById(id).data['describe']
            });
            ordernum = new Ext.form.Hidden({
                fieldLabel: '码表编号',
                id:'modordernum',
                name: 'ordernum',
                width:100,
                allowBlank:false,
                maxLength:4,
                maxLengthText:"最大长度4",
                value:gridStore.getById(id).data['ordernum']
            });
            code= new Ext.form.TextField({
                fieldLabel: '编码',
                id:'modcode',
                name: 'code',
                width:200,
                allowBlank:false,
                maxLength:20,
                maxLengthText:"最大长度20",
                value:gridStore.getById(id).data['code']
            });
            ddId = new Ext.form.Hidden({
                name:'ddId',
                id:'ddId',
                value:id
            });
             dtype = new Ext.ux.RadioGroup({
            fieldLabel : '类型',
            defaultValue:gridStore.getById(id).data['ddType'],
			// xtype:'radiogroup',//表单文本框
			 horizontal:true,
			 maxLength : 200,
			value: gridStore.getById(id).data['ddType'],
			 name :'ddType',
			 radios:getRadios(typeStore)
        });
            if (modformPanel != null) {
                modformPanel.destroy(true);
                modformPanel = null;
            }
            if (!modformPanel) {
                modformPanel = new Ext.FormPanel({
                    labelWidth: 125,
                    labelAlign:"right",
                    url: '../../dataDictionary/updateTddDefinition.action',
                    frame:false,
                    bodyStyle:'padding:60px 5px 0',
                    items: [code,nbcode,ordernum,name,dtype,describe,ddId,remark]
                });
            }
            if (modwin != null) {
                modwin.destroy(true);
                modwin = null;
            }
            if (!modwin) {
                modwin = new Ext.Window({
                    id : 'modformWin',
                    title: '修改记录',
                    width: 520,
                    height:370,
                    minWidth: 200,
                    minHeight: 200,
                    xtype:'window',
                    maximizable : false,
                    closeAction : 'hide',
                    layout: 'fit',
                    plain:false,
                    closable:true,
                    modal:false,
                    border:false,
                    bodyStyle:'padding:5px;',
                    buttonAlign:'center',
                    items: modformPanel,
                    buttons: [{
                        handler: function() {
                            if (modformPanel.getForm().isValid()) {
                                modformPanel.getForm().submit({
                                    waitMsg: '正在处理，请稍等...',
                                    reset: true,
                                    failure: function(form, action) {
                                        Ext.MessageBox.hide();
                                        Ext.Msg.show({
                                            title: '错误',
                                            msg: '<span style="text-align:center;width:250px;margin:5 0 5 0;">' + action.result.msg + '</span>',
                                            buttons: Ext.MessageBox.OK,
                                            icon: Ext.MessageBox.WARNING
                                        });
                                    },
                                    success: function(form, action) {
                                        Ext.MessageBox.hide();
                                        Ext.Msg.show({
                                            title: '成功',
                                            msg: '<span style="text-align:center;width:250px;margin:5 0 5 0;">' + action.result.msg + '</span>',
                                            buttons: Ext.MessageBox.OK,
                                            icon: Ext.MessageBox.INFO
                                        });
                                        modwin.hide();
                                        gridStore.reload();
                                    },
                                    method:'POST'
                                });
                            }
                        },
                        text: '保存'
                    },{
                        handler: function() {
                            modwin.hide();
                        },
                        text: '取消'
                    }]
                });
            }
            modwin.show();
        }
    }

    function onDelClick(item) {
        var selectedCount = sm.getCount();
        if (selectedCount == 0) {
            Ext.Msg.alert('删除操作', '未选中要删除的数据，请选择要删除的数据！');
            return;
        } else {
            Ext.Msg.confirm('删除记录', '请确认要删除记录吗?按是将删除选中记录！', function(btn) {
                if (btn == 'yes') {
                    var records = sm.getSelections();
                    var _ids = '';
                    for (var i = 0; i < records.length; i++) {
                        _ids += records[i].id;
                        _ids += '_';
                    }
                    Ext.MessageBox.wait('正在处理，请稍等...');
                    Ext.Ajax.request({
                        url:  '../../dataDictionary/deleteTddDefinition.action',
                        failure: function(result, request) {
                            Ext.MessageBox.hide();
                            Ext.Msg.show({
                                title: '错误',
                                msg: '<span style="text-align:center;width:250px;margin:5 0 5 0;">' + '删除失败！' + '</span>',
                                buttons: Ext.MessageBox.OK,
                                icon: Ext.MessageBox.WARNING
                            });
                        },
                        success: function(result, request) {
                            Ext.MessageBox.hide();
                            Ext.Msg.show({
                                title: '成功',
                                msg: '<span style="text-align:center;width:250px;margin:5 0 5 0;">' + '删除成功！' + '</span>',
                                buttons: Ext.MessageBox.OK,
                                icon: Ext.MessageBox.INFO
                            });
                            gridStore.reload();
                        },
                        params: { ddID: _ids}
                    });
                }
            });
        }
    }

    var gridStore = new Ext.data.Store({
        proxy: new Ext.data.ScriptTagProxy({
            url: '../../dataDictionary/buildJSONString.action'
        }),
        reader: new Ext.data.JsonReader({
            root: 'results',
            totalProperty: 'total',
            id: 'ddId'
        }, [
            {name: 'ddId', mapping: 'ddId'},
            {name: 'name', mapping: 'name'},
            {name: 'code', mapping: 'code'},
            {name: 'ddType', mapping: 'ddType'},
            {name: 'describe', mapping: 'describe'},
            {name: 'remark', mapping: 'remark'},
             {name: 'nbcode', mapping: 'nbcode'},
            {name: 'ordernum', mapping: 'ordernum'}
        ]),
        sortInfo:{field: 'nbcode', direction: 'ASC'},
  
        remoteSort: false
    });


    function onQueryClick(item) {


        gridStore.proxy = new Ext.data.ScriptTagProxy({
            url:encodeURI( '../../dataDictionary/buildJSONString.action?nameQuery=' + nameQuery.getValue()
                    + '&describeQuery=' + describeQuery.getValue()+'&idQuery='+idQuery.getValue())
        });
        gridStore.reload({params:{start:0, limit:pageSize}});


    }

    var sm = new Ext.grid.CheckboxSelectionModel();
    //    sm.locked = true;

 //   var cm = new Ext.grid.LockingColumnModel([sm, {
    var cm = new Ext.ux.grid.LockingColumnModel([sm, {
        id: 'code',
        header: "编码",
        dataIndex: 'code',
        align:'center',
        width: 100,
        sortable: false,
     //   hidden:true,
        css: 'white-space:normal;border:#eee solid;border-width:0 0 0 1;vertical-align:middle;'
    },
        {
        id: 'code',
        header: "编码",
        dataIndex: 'code',
        width:120,
        align:'center',
             hidden:true,
        sortable: false,
        css: 'white-space:normal;border:#eee solid;border-width:0 1 0 1;vertical-align:middle;'
    },{
        id: 'name',
        header: "码表名称",
        dataIndex: 'name',
        width: 180,
        align:'center',
        sortable: false,
        locked:false,
        renderer:function (value) {
            return "<div align=left>" + value + "</div>"
        },
        css: 'white-space:normal;border:#eee solid;border-width:0 1 0 1;vertical-align:middle;'
    },   {
        id: 'ddType',
        header: "类型",
        dataIndex: 'ddType',
        width: 80,
        align:'center',
      //  hidden:true,
        renderer:function (value) {
            if (value == '1') return "简单码表";
            else if (value == '2') return "树形码表";
            else return "";

        },
        sortable: false,
        css: 'white-space:normal;border:#eee solid;border-width:0 0 0 1;vertical-align:middle;'
    } ,{
		id : 'inputButton',
		header : "维护",
		dataIndex : 'inputButton',
		align : 'center',
		width : 80,
		hidden : false,
		sortable : true,
		renderer : renderBtn,
		css : 'white-space:normal;border:#eee solid;border-width:0 0 0 1;height:30;vertical-align:middle;'
	},
        {
            id: 'describe',
            header: "码表说明",
            dataIndex: 'describe',
            align:'center',
            width: 320,
            hidden:false,
            sortable: false,
            locked:false,
            renderer:function (value) {
                return "<div align=left>" + value + "</div>"
            },
            css: 'white-space:normal;border:#eee solid;border-width:0 0 0 1;vertical-align:middle;'
        } , {
        id: 'ddId',
        header: "码表ID",
             align:'center',
        dataIndex: 'ddId',
        width: 60,
        sortable: true,
      //  hidden:true,
        css: 'white-space:normal;border:#eee solid;border-width:0 0 0 1;vertical-align:middle;'
    }, 

             {
            id: 'remark',
            header: "开发公司",
            dataIndex: 'remark',
            align:'center',
            width: 120,
            hidden:true,
            sortable: false,
            locked:false,
            renderer:function (value) {
                return "<div align=center>" + value + "</div>"
            },
            css: 'white-space:normal;border:#eee solid;border-width:0 0 0 1;vertical-align:middle;'
        }

    ]);

    //var grid = new Ext.grid.LockingGridPanel({
    grid = new Ext.ux.grid.SSNJLOCKPAGEGrid({
       // el:'grid-div',
        id:'grid',
        layout:'fit',
        store:gridStore ,
        height:gridHeight,
        loadMask: {msg:'正在加载数据，请稍候……'},
        cm:cm,
        sm: sm,
        viewConfig: {
            enableRowBody:false
            //            forceFit:true
        },
        bodyStyle:'width:100%;',
       // tbar:[addButton, '-', modButton, '-', delButton,'-',managerButon],
         tbar:['名称:',nameQuery,'说明:',describeQuery,queryButton,addButton, '-', modButton, '-', delButton],
        frame:false,
        border:false,
        stripeRows:true
        //bbar:pagingToolbar
    });

   // grid.render();
    grid.render(Ext.get('grid-div'));
    gridStore.load({params:{start:0, limit:pageSize}});


})